<template>
  <div :class="$style.container">
    <div :class="$style.header">
      <van-row type="flex" justify="space-between">
        <div :class="$style.headerText">{{ title }}</div>
      </van-row>
    </div>
    <div v-if="list && list.length > 0" :class="$style.contentLayout">
      <div v-if="parseInt(list[answerIndex].category) === 0" :class="$style.content">
        <van-row type="flex" justify="space-between">
          <van-col span="12" :class="$style.contentTitle">单项选择题 </van-col>
          <van-col span="12" :class="$style.contentCount">
            <span :class="$style.doCount">{{ answerIndex + 1 }}</span
            >/{{ list.length }}</van-col
          >
        </van-row>
        <div :class="$style.questionTitle">
          {{ answerIndex + 1 }}、{{ list[answerIndex].title }}
        </div>
        <div
          v-if="list[answerIndex].titleImages != null && list[answerIndex].titleImages.length > 0"
        >
          <img v-for="(it, i) in list[answerIndex].titleImages" :key="i" :src="it" />
        </div>

        <div>
          <van-row
            v-for="(item, index) in list[answerIndex].optionCount"
            :key="index"
            :class="$style.questionContainer"
            @click="doQuestion(0, [list[answerIndex].option[index].sort])"
          >
            <van-col
              span="4"
              :class="
                list[answerIndex].answer &&
                list[answerIndex].answer[0] === list[answerIndex].option[index].sort
                  ? [$style.questionOption, $style.questionOptionActive]
                  : $style.questionOption
              "
              >{{ option[index] }}</van-col
            >
            <van-col
              v-if="list[answerIndex].option[index].answerType == 0"
              span="20"
              :class="$style.questionContent"
            >
              {{ list[answerIndex].option[index].answer }}
            </van-col>
            <van-col v-else span="20" :class="$style.questionContent">
              <img :src="list[answerIndex].option[index].answerImage" />
            </van-col>
          </van-row>
        </div>
      </div>

      <div v-else-if="parseInt(list[answerIndex].category) === 1" :class="$style.content">
        <van-row type="flex" justify="space-between">
          <van-col span="12" :class="$style.contentTitle">多项选择题 </van-col>
          <van-col span="12" :class="$style.contentCount">
            <span :class="$style.doCount">{{ answerIndex + 1 }}</span
            >/{{ list.length }}</van-col
          >
        </van-row>
        <div :class="$style.questionTitle">
          {{ answerIndex + 1 }}、{{ list[answerIndex].title }}
        </div>
        <div
          v-if="list[answerIndex].titleImages != null && list[answerIndex].titleImages.length > 0"
        >
          <img v-for="(it, i) in list[answerIndex].titleImages" :key="i" :src="it" />
        </div>

        <div>
          <van-row
            v-for="(item, index) in list[answerIndex].optionCount"
            :key="index"
            :class="$style.questionContainer"
            @click="doQuestion(1, list[answerIndex].option[index].sort)"
          >
            <van-col
              span="4"
              :class="
                list[answerIndex].answer &&
                list[answerIndex].answer.includes(list[answerIndex].option[index].sort)
                  ? [$style.questionOption, $style.questionOptionActive]
                  : $style.questionOption
              "
              >{{ option[index] }}</van-col
            >
            <van-col
              v-if="list[answerIndex].option[index].answerType == 0"
              span="20"
              :class="$style.questionContent"
            >
              {{ list[answerIndex].option[index].answer }}
            </van-col>
            <van-col v-else span="20" :class="$style.questionContent">
              <img :src="list[answerIndex].option[index].answerImage" />
            </van-col>
          </van-row>
        </div>
      </div>

      <div v-else-if="parseInt(list[answerIndex].category) === 2" :class="$style.content">
        <van-row type="flex" justify="space-between">
          <van-col span="12" :class="$style.contentTitle">判断题 </van-col>
          <van-col span="12" :class="$style.contentCount">
            <span :class="$style.doCount">{{ answerIndex + 1 }}</span
            >/{{ list.length }}</van-col
          >
        </van-row>
        <div :class="$style.questionTitle">
          {{ answerIndex + 1 }}、{{ list[answerIndex].title }}
        </div>
        <div
          v-if="list[answerIndex].titleImages != null && list[answerIndex].titleImages.length > 0"
        >
          <img v-for="(it, i) in list[answerIndex].titleImages" :key="i" :src="it" />
        </div>

        <div>
          <van-row :class="$style.questionContainer" @click="doQuestion(2, [0])">
            <van-col
              span="4"
              :class="
                list[answerIndex].answer && list[answerIndex].answer[0] === 0
                  ? [$style.questionOption, $style.questionOptionActive]
                  : $style.questionOption
              "
              >A
            </van-col>
            <van-col span="20" :class="$style.questionContent"> 正确 </van-col>
          </van-row>
          <van-row :class="$style.questionContainer" @click="doQuestion(2, [1])">
            <van-col
              span="4"
              :class="
                list[answerIndex].answer && list[answerIndex].answer[0] === 1
                  ? [$style.questionOption, $style.questionOptionActive]
                  : $style.questionOption
              "
            >
              B</van-col
            >
            <van-col span="20" :class="$style.questionContent"> 错误 </van-col>
          </van-row>
        </div>
      </div>

      <div v-else-if="parseInt(list[answerIndex].category) === 3" :class="$style.content">
        <van-row type="flex" justify="space-between">
          <van-col span="12" :class="$style.contentTitle">填空题 </van-col>
          <van-col span="12" :class="$style.contentCount">
            <span :class="$style.doCount">{{ answerIndex + 1 }}</span
            >/{{ list.length }}</van-col
          >
        </van-row>
        <div :class="$style.questionTitle">
          {{ answerIndex + 1 }}、{{ list[answerIndex].title }}
        </div>
        <div
          v-if="list[answerIndex].titleImages != null && list[answerIndex].titleImages.length > 0"
        >
          <img v-for="(it, i) in list[answerIndex].titleImages" :key="i" :src="it" />
        </div>

        <div>
          <div :class="$style.questionContainer">
            <van-field
              v-for="(item, index) in list[answerIndex].optionCount"
              :key="index"
              :value="
                list[answerIndex].answer && list[answerIndex].answer[index]
                  ? list[answerIndex].answer[index]
                  : ''
              "
              :placeholder="`${index + 1}、请填空`"
              @input="
                (e) => {
                  doQuestion(3, e, index);
                }
              "
            />
          </div>
        </div>
      </div>

      <div v-else-if="parseInt(list[answerIndex].category) === 4" :class="$style.content">
        <van-row type="flex" justify="space-between">
          <van-col span="12" :class="$style.contentTitle" placeholder="请填空"> 简答题 </van-col>
          <van-col span="12" :class="$style.contentCount" placeholder="请填空">
            <span :class="$style.doCount">{{ answerIndex + 1 }}</span
            >/{{ list.length }}</van-col
          >
        </van-row>
        <div :class="$style.questionTitle">
          {{ answerIndex + 1 }}、{{ list[answerIndex].title }}
        </div>
        <div
          v-if="list[answerIndex].titleImages != null && list[answerIndex].titleImages.length > 0"
        >
          <img v-for="(it, i) in list[answerIndex].titleImages" :key="i" :src="it" />
        </div>

        <div>
          <div :class="$style.questionContainer">
            <van-field
              :value="list[answerIndex].answer ? list[answerIndex].answer[0] : ''"
              rows="8"
              type="textarea"
              maxlength="1000"
              placeholder="请输入你的答案"
              show-word-limit
              :class="$style.area"
              @input="
                (e) => {
                  doQuestion(4, [e]);
                }
              "
            />
          </div>
        </div>
      </div>
    </div>

    <van-row type="flex" justify="space-between" :class="$style.submit" align="center">
      <div :class="$style.optionDiv">
        <img :class="$style.answerView" src="../../assets/view-answer.png" @click="viewAnswer" />
        <van-col @click="viewAnswer">
          已答
          <span :class="$style.doCount">{{ doCount }}</span
          >/{{ list.length }}</van-col
        >
        <div :class="$style.optionBtn">
          <van-button
            type="default"
            round
            :disabled="answerIndex === 0"
            :class="$style.pre"
            @click="nextAndPreQuestion('pre')"
          >
            上一题
          </van-button>

          <van-button
            type="default"
            round
            :disabled="this.answerIndex === this.list.length - 1"
            :class="$style.next"
            @click="nextAndPreQuestion('next')"
          >
            下一题
          </van-button>
        </div>
      </div>

      <van-col span="16" :class="[this.$style.noSubmitBtn, this.$style.submitBtn]" @click="submit">
        提交</van-col
      >
    </van-row>

    <van-popup
      v-model="show"
      closeable
      close-icon="close"
      position="bottom"
      :style="{ height: '70%' }"
    >
      <van-row :class="$style.replyContainer">
        <van-col
          v-for="(item, index) in list"
          :key="index"
          :class="item.answer && item.answer.length > 0 ? $style.reply : $style.noreply"
          @click="goQuestion(index)"
        >
          {{ index + 1 }}
        </van-col>
      </van-row>
    </van-popup>

    <div v-if="loading" :class="$style.loading">
      <van-loading color="#3EAD68" size="24px" vertical>加载中...</van-loading>
    </div>

    <!-- <canvas-signature ref="signature" @confirm="uploadSignature" /> -->

    <van-loading v-if="upLoading" color="#3EAD68" size="24px" vertical>试卷提交中...</van-loading>
  </div>
</template>
<script>
import Store from '@/store';
// import OSS from 'ali-oss';
// import * as ClientJSAPIHelpers from '@/helpers/client-jsapi';
import { Col, Row, Button, Popup, Field, Loading, Toast, Dialog } from 'vant';
import { GetWorkDetail, CommitWork, GetTrainDetail, LearnTrain } from '@/apis';
import wx from 'weixin-js-sdk';
export default {
  name: 'Examing',
  components: {
    'van-row': Row,
    'van-col': Col,
    'van-button': Button,
    'van-popup': Popup,
    'van-field': Field,
    'van-loading': Loading,
  },
  Store,
  data() {
    return {
      show: false,
      loading: false,
      list: [],
      /**试卷名称 */
      title: '',
      /**倒计时 */
      countDown: '',
      /**当前题号 */
      answerIndex: 0,
      option: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'],
      /**做了多少题 */
      doCount: 0,
      /**oss */
      ossConfig: {},
      /**oss对象 */
      clent: {},
      /**解析url上面的id */
      urlId: '',
      /**提交的loading */
      upLoading: false,
    };
  },
  mounted() {
    const isCacheQuestion = !!window.localStorage.getItem(`work${this.id}`);
    this.id = this.$router.history.current.query.id;
    this.type = this.$router.history.current.query.type;
    var lessonId = this.$router.history.current.query.lessonId; //缓存lessonId
    if (!lessonId) {
      lessonId = sessionStorage.getItem('lessonId');
    } else {
      sessionStorage.setItem('lessonId', lessonId);
    }
    this.lessonId = lessonId;

    this.loading = true;
    /**获取试卷详情 */
    /**获取Oss配置 */
    this._getDetail().then((res) => {
      this.title = res.data.title;
      this.list = this._formatExercises(res.data.exercises);
      //读取缓存
      if (isCacheQuestion) {
        let num = 0;
        const data = JSON.parse(window.localStorage.getItem(`work${this.id}`));
        this.answerIndex = data.index === this.list.length - 1 ? data.index : data.index + 1;
        this.list.map((item) => {
          for (const key in data.cacheAnswer) {
            if (item.id == key) {
              num++;
              item.answer = data.cacheAnswer[key];
              break;
            }
          }
          return item;
        });
        this.doCount = num;
      }
    });
    this.loading = false;
  },

  methods: {
    _getDetail() {
      if (this.type == 1) {
        return GetWorkDetail(this.id);
      } else {
        return GetTrainDetail(this.id);
      }
    },
    viewAnswer() {
      this.show = true;
    },
    _getRemainDuration(endDate) {
      return (new Date(endDate).getTime() - new Date().getTime()) / 1000;
    },
    _formatExercises(list) {
      return list.map((x) => {
        x.optionCount = x.option.length;
        return x;
      });
    },
    /**缓存试题 */
    cacheExam(cacheAnswer) {
      window.localStorage.setItem(
        `paper${this.id}`,
        JSON.stringify({ cacheAnswer, index: this.answerIndex }),
      );
    },
    // 上一题下一题
    nextAndPreQuestion(type) {
      let isDoExam = false;
      const cacheAnswer = {};
      this.list.forEach((item) => {
        if (item.answer && item.answer.length > 0) {
          isDoExam = true;
          cacheAnswer[[item.id]] = item.answer;
        }
      });
      if (isDoExam) this.cacheExam(cacheAnswer);
      if (type === 'next' && this.answerIndex < this.list.length) this.answerIndex++;
      if (type === 'pre' && this.answerIndex > 0) this.answerIndex--;
    },
    /**
     * 做题时候的处理函数
     * @method
     * @param {number} type 类型 1:单选;2:多选;3:判断;4:填空;5:主观
     * @param {string} answer 答案
     * @param {string} fillIndex 填空题的索引
     *
     */
    doQuestion(type, answer, fillIndex) {
      this.list = this.list.map((item, index) => {
        if (type === 0 || type === 2 || type === 4) {
          if (index === this.answerIndex) {
            if (answer[0] === '') return { ...item, answer: '' };
            return { ...item, answer };
          }
          return item;
        }
        if (type === 1) {
          //匹配
          if (index === this.answerIndex) {
            // 选择和取消
            if (item.answer) {
              if (item.answer.includes(answer))
                return { ...item, answer: item.answer.filter((item) => item !== answer) };
              else return { ...item, answer: [...item.answer, answer] };
            } else {
              return { ...item, answer: [answer] };
            }
          }
          return item;
        }

        if (type === 3) {
          if (index === this.answerIndex) {
            // 选择和取消
            if (item.answer) {
              item.answer[fillIndex] = answer;
              if (answer === '') {
                let flag = true;
                item.answer.map((item) => {
                  if (item !== '') {
                    flag = false;
                  }
                });
                if (flag) {
                  item.answer = [];
                  return item;
                }
              }
              return item;
            } else {
              const tmp = [];
              tmp[fillIndex] = answer;
              return { ...item, answer: tmp };
            }
          }
          return item;
        }
      });

      let num = 0;
      this.list.forEach((item) => {
        if (item.answer && item.answer.length > 0) {
          num++;
        }
      });
      this.doCount = num;
    },
    /**提交试卷 */
    submit() {
      var unSelectCount = this.list.length - this.doCount;
      Dialog.confirm({
        title: '提示',
        message:
          unSelectCount > 0
            ? `您还有${this.list.length - this.doCount}道题未完成,是否提交？`
            : '是否提交？',
      }).then(() => {
        this._commitWork();
      });
    },
    _commitWork() {
      const answers = [];
      this.list.map((item) => {
        if (item.answer != null) {
          answers.push({
            id: item.id,
            answer: item.answer.map((ans) => {
              return ans + '';
            }),
          });
        }
      });
      if (this.type == 1) {
        CommitWork(this.id, answers).then((res) => {
          if (res.code == 0) {
            this.upLoading = false;
            Toast.success('提交成功');
            wx.miniProgram.navigateBack();
          }
        });
      } else {
        LearnTrain(this.id).then((res) => {
          if (res.code == 0) {
            this.upLoading = false;
            Toast.success('提交成功');
            wx.miniProgram.navigateBack();
          }
        });
      }
    },

    /**上传签名图片以及提交答案 */
    uploadSignature(file) {
      console.log(file);
    },
    /**快速切换试题 */
    goQuestion(index) {
      this.answerIndex = index;
      this.show = false;
    },
  },
};
</script>
<style lang="less" module>
div::-webkit-scrollbar {
  width: 0;
}

.container {
  img {
    max-width: 100%;
    margin-bottom: 5px;
  }
  // display: grid;
  // grid-template-rows: 50px 1fr 120px;
  // padding-bottom: 120px;
  // padding-top: 50px;
  display: flex;
  flex-direction: column;
  font-size: 14px;
  color: #333333;
  height: 100vh;
  .optionDiv {
    display: flex;
    align-items: center;
    height: 50px;
    width: 100%;
    .answerView {
      height: 16px;
      width: 16px;
      margin-right: 12px;
    }
    .optionBtn {
      flex-grow: 1;
      display: flex;
      justify-content: flex-end;
    }
  }
  .doCount {
    color: #025036;
  }

  .header {
    border-radius: 6px;
    background-color: white;
    height: 44px;
    margin: 8px 15px;
    padding: 8px 15px;
  }
  .headerText {
    font-weight: 600;
    font-size: 12px;
    line-height: 44px;
  }
  .headerTime {
    line-height: 44px;
    font-weight: 500;
    font-size: 12px;
    color: #fe952c;
    text-align: right;
  }
  .contentLayout {
    flex-grow: 1;
    overflow: scroll;
  }
  .content {
    border-radius: 6px;
    margin: 10px 15px;
    background-color: white;
    padding: 15px;
    .contentTitle {
      font-weight: 600;
      color: #025036;
    }

    .contentCount {
      text-align: right;
      color: #999;
    }
    .questionTitle {
      padding: 16px 0;
      font-weight: 600;
    }
    .questionContainer {
      margin-bottom: 15px;
    }
    .questionOption {
      width: 30px;
      height: 30px;
      background: #ffffff;
      border: 0.5px solid #d9d9d9;
      border-radius: 50%;
      line-height: 30px;
      text-align: center;
    }
    .questionOptionActive {
      background: #025036;
      color: white;
    }
    .questionContent {
      font-size: 13px;
      line-height: 30px;
      padding-left: 15px;
    }
  }
  .footer {
    text-align: center;
  }
  .pre {
    width: 100px;
    height: 40px;
    background: #ffffff;
    margin-right: 10px;
  }
  .next {
    width: 100px;
    height: 40px;
    background: #ffffff;
    // color: white;
  }
  .submit {
    width: 100%;
    background: white;
    color: #999999;
    padding: 8px 16px;
    .noSubmitBtn {
      text-align: center;
      width: 100%;
      height: 40px;
      line-height: 40px;
      background: #bbbbbb;
      border-radius: 6px;
      color: white;
      font-weight: 500;
    }
    .submitBtn {
      background: #025036;
    }
  }
  .replyContainer {
    padding: 40px 20px;
  }
  .reply {
    width: 40px;
    height: 40px;
    line-height: 40px;
    border: 0.5px solid #d9d9d9;
    border-radius: 50%;
    background: #025036;
    color: white;
    text-align: center;
    margin-right: 15px;
    margin-bottom: 15px;
  }
  .noreply {
    width: 40px;
    height: 40px;
    line-height: 40px;
    border: 0.5px solid #d9d9d9;
    border-radius: 50%;
    background: white;
    text-align: center;
    margin-right: 15px;
    margin-bottom: 15px;
  }
  .area {
    border: 0.5px solid #f0f0f0;
    border-radius: 6px;
  }
  .loading {
    padding-top: 50%;
    top: 0;
    position: absolute;
    height: 100vh;
    width: 100%;
    background: white;
    z-index: 99;
  }
}
</style>
